package com.dalei.vds;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.dalei.vds.dao.LogDao;
import com.dalei.vds.environment.CurrentTask;
import com.dalei.vds.environment.SystemStatus;
import com.dalei.vds.settings.DeviceSettings;
import com.dalei.vds.soap.DetectionSoapImpl;
import com.dalei.vdserver.shared.model.DetectionTask;
import com.dalei.vdserver.shared.soap.DetectionSoap;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class SelectorActivity extends Activity {
	
	public static final int REQUEST_CONFIRM = 0x00000020;

	private static final int MESSAGE_SHOW_PROGRESS_DIALOG = 0x00000000;

	private static final int MESSAGE_DISMISS_PROGRESS_DIALOG = 0x00000001;

	private static final int MESSAGE_SHOW_TOAST = 0x00000002;

	private static final int MESSAGE_LOAD_TASKS = 0x00000003;

	private static final int MESSAGE_SET_COUNT = 0x00000004;
	
	private static final String FIELD_FID = "fid";

	private static final String FIELD_LICENSE_PLATE_NUMBER = "licensePlateNumber";

	private ListView vehicleListView;

	private TextView workerText;

	private TextView countText;

	private Button refreshBtn;

	private Dialog dialog;

	private List<Map<String, Object>> taskList;
	
	private Handler handler;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.selector);

		taskList = new ArrayList<Map<String, Object>>();

		handler = new IncomingHandler(this);

		vehicleListView = (ListView) findViewById(R.id.selector_list_vehicle);
		vehicleListView.setAdapter(new SimpleAdapter(this, taskList,
				android.R.layout.simple_list_item_1,
				new String[] { FIELD_LICENSE_PLATE_NUMBER },
				new int[] { android.R.id.text1 }));
		vehicleListView.setOnItemClickListener(new OnItemClickListener() {

			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				int fid = 0;
				Object object = parent.getAdapter().getItem(position);
				if (object instanceof Map<?, ?>) {
					Map<String, Object> map = (Map<String, Object>) object;
					fid = (Integer) map.get(SelectorActivity.FIELD_FID);
					CurrentTask.setFid(fid);

					Intent intent = new Intent();
					intent.setClass(SelectorActivity.this,
							ConfirmActivity.class);
					SelectorActivity.this.startActivityForResult(intent,
							REQUEST_CONFIRM);
				} else {
					Toast.makeText(
							SelectorActivity.this,
							SelectorActivity.this
									.getString(R.string.internal_error),
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		workerText = (TextView) findViewById(R.id.selector_text_worker);
		workerText.setText(SystemStatus.getUserName());

		countText = (TextView) findViewById(R.id.selector_text_count);

		refreshBtn = (Button) findViewById(R.id.selector_btn_refresh);
		refreshBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				// TODO Auto-generated method stub
				refreshTask();
			}
		});

		refreshTask();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		case REQUEST_CONFIRM:
			refreshTask();
			break;

		default:
			break;
		}
	}

	private void refreshTask() {
		Thread thread = new OnLoadThread(this);
		thread.start();
	}

	private static class IncomingHandler extends Handler {

		private WeakReference<SelectorActivity> reference;

		public IncomingHandler(SelectorActivity activity) {
			// TODO Auto-generated constructor stub
			reference = new WeakReference<SelectorActivity>(activity);
		}

		@Override
		@SuppressWarnings("unchecked")
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			final SelectorActivity activity = reference.get();

			switch (msg.what) {

			case MESSAGE_SHOW_PROGRESS_DIALOG:
				activity.dialog = ProgressDialog.show(activity, null,
						activity.getString(R.string.waitting));
				break;

			case MESSAGE_DISMISS_PROGRESS_DIALOG:
				activity.dialog.dismiss();
				break;

			case MESSAGE_SHOW_TOAST:
				Toast.makeText(activity, activity.getString(msg.arg1),
						Toast.LENGTH_SHORT).show();
				break;

			case MESSAGE_LOAD_TASKS:
				ArrayAdapter<String> adapter = (ArrayAdapter<String>) activity.vehicleListView
						.getAdapter();
				adapter.notifyDataSetChanged();
				break;

			case MESSAGE_SET_COUNT:
				activity.countText.setText(Integer.toString(msg.arg1));
				break;

			default:
				break;
			}
		}
	}

	private class OnLoadThread extends Thread {

		private SelectorActivity activity;

		public OnLoadThread(SelectorActivity activity) {
			// TODO Auto-generated constructor stub
			this.activity = activity;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			activity.handler
					.sendEmptyMessage(SelectorActivity.MESSAGE_SHOW_PROGRESS_DIALOG);
			Calendar calendar = new GregorianCalendar();
			final int YEAR = calendar.get(Calendar.YEAR);
			final int MONTH = calendar.get(Calendar.MONTH);
			final int DATE = calendar.get(Calendar.DATE);
			calendar.set(YEAR, MONTH, DATE,
					calendar.getMinimum(Calendar.HOUR_OF_DAY),
					calendar.getMinimum(Calendar.MINUTE),
					calendar.getMinimum(Calendar.SECOND));
			Date start = calendar.getTime();
			calendar.set(YEAR, MONTH, DATE,
					calendar.getMaximum(Calendar.HOUR_OF_DAY),
					calendar.getMaximum(Calendar.MINUTE),
					calendar.getMaximum(Calendar.SECOND));
			Date end = calendar.getTime();
			LogDao dao = new LogDao(activity);
			int count = dao.getCountByTime(start, end);
			Message msg = activity.handler.obtainMessage();
			msg.what = SelectorActivity.MESSAGE_SET_COUNT;
			msg.arg1 = count;
			activity.handler.sendMessage(msg);
			DetectionSoap soap = new DetectionSoapImpl(activity);
			DeviceSettings deviceSettings = new DeviceSettings(activity);
			int deviceId = deviceSettings.getDeviceId();
			List<DetectionTask> tasks = soap.getDetectionTasks(deviceId);
			if (tasks != null) {
				if (tasks.size() > 0) {
					List<Map<String, Object>> taskList = new ArrayList<Map<String, Object>>();
					for (DetectionTask task : tasks) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put(SelectorActivity.FIELD_FID, task.getFid());
						map.put(SelectorActivity.FIELD_LICENSE_PLATE_NUMBER,
								task.getLicensePlateNumber());
						taskList.add(map);
					}
					msg = activity.handler.obtainMessage();
					msg.what = MESSAGE_LOAD_TASKS;
					msg.obj = taskList;
					activity.handler.sendMessage(msg);
					activity.handler
							.sendEmptyMessage(SelectorActivity.MESSAGE_DISMISS_PROGRESS_DIALOG);
				} else {
					activity.handler
							.sendEmptyMessage(SelectorActivity.MESSAGE_DISMISS_PROGRESS_DIALOG);
					msg = activity.handler.obtainMessage();
					msg.what = SelectorActivity.MESSAGE_SHOW_TOAST;
					msg.arg1 = R.string.no_task;
					activity.handler.sendMessage(msg);
				}
			} else {
				msg = activity.handler.obtainMessage();
				msg.what = SelectorActivity.MESSAGE_SHOW_TOAST;
				msg.arg1 = R.string.load_vehicles_failed;
				activity.handler.sendMessage(msg);
			}
		}
	}
}
